<?php

namespace App\Console\Commands\Cashbook;

use App\Library\Rms\RmsShopApi;
use App\Models\Cashbook\CashbookModel;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class RmsOrdersUpdateSync extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cashbook:rms_orders_update_sync';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '记账本Rms中非当日订单更新通知，如隔天退款，同步隔天离线订单等变更同步';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $dateArray = Redis::sMembers(CashbookModel::RMS_ORDERS_UPDATE_DATE);//获取所有变更日期
        Log::info('rms_orders_update_sync:date', ['dateArray' => $dateArray]);
        if (!$dateArray) {
            return false;
        }

        foreach ($dateArray as $date) {
            if ($date == date('Y-m-d') && config('app.env') == 'prod') {
                continue;
            }
            $shopIdArray = Redis::sMembers(CashbookModel::RMS_ORDERS_UPDATE_DATE_SHOP_ID . $date);//获取所有变更门店id

            Log::info('rms_orders_update_sync:shopId', ['date' => $date, 'shopIdArray' => $shopIdArray]);
            if ($shopIdArray) {
                foreach ($shopIdArray as $shopId) {
                    $cashbookModel = CashbookModel::getInfoByRecordTime($shopId, strtotime($date), CashbookModel::CATEGORY_1, CashbookModel::SOURCE_SYSTEM_ADD);
                    $amount        = (new RmsShopApi())->originalPrice($shopId, strtotime($date), strtotime($date) + 86399)['data']['realPayPrice'] ?? 0;//取店铺营业额数据

                    if ($cashbookModel && $cashbookModel->amount != $amount) {//营业收入不匹配进行修改
                        CashbookModel::query()->where('id', $cashbookModel->id)->update(['amount' => $amount]);
                    }
                }
            }
            Redis::sRem(CashbookModel::RMS_ORDERS_UPDATE_DATE, $date);   //移除日期
            Redis::del(CashbookModel::RMS_ORDERS_UPDATE_DATE_SHOP_ID . $date);//删除日期对应门店id key
        }
    }
}
